<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="applyTitle">
            <el-input v-model="form.applyTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <template>
              <router-link
                target="_blank"
                :to="{path:'/fund/fundBasehome',query:{id:form.fundId}}"
                class="link_a"
              >{{ form.fundName }} </router-link>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('总认缴金额')+ $t('金额单位')" prop="totalSubscriptionAmount">
            <Money v-model="form.totalSubscriptionAmount" :placeholder="$t('总认缴金额')" unit="w" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否基金扩大募集')">
            <el-radio-group v-model="form.isFundEnlarge">
              <el-radio
                v-for="dict in isFundEnlargeOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.isFundEnlarge === 'Y'" :span="12">
          <el-form-item :label="$t('增加新增认缴金额')+ $t('金额单位')" prop="addSubscribedAmount">
            <Money v-model="form.addSubscribedAmount" :placeholder="$t('增加新增认缴金额')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('出资人列表') }}</span>
      </div>
      <el-table :data="form.fundAgreementLpList" class="nowrapTable formTable" border>
        <el-table-column :label="$t('出资人类型')" align="center" :prop="type" :formatter="typeFormat" />
        <el-table-column :label="$t('出资人名称')" align="center" :prop="userName">
          <template slot-scope="scope">
            <span>{{ scope.row.userName }} </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('合伙人类型')" align="center" :prop="partnerType" :formatter="partnerTypeFormat" />
        <el-table-column :label="$t('认缴时间')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('认缴时间') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundAgreementLpList.' + scope.$index + '.timeSubscription'" :rules="AgreementLpListRules.timeSubscription">
              <DatePicker v-model="scope.row.timeSubscription" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('认缴金额')+ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundAgreementLpList.' + scope.$index + '.subscribedAmount'" :rules="AgreementLpListRules.subscribedAmount">
              <Money v-model="scope.row.subscribedAmount" unit="w" @change="percentageCalculation" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('认缴比例(%)')" align="center" :prop="subscribedRatio">
          <template slot-scope="scope">
            <span>{{ scope.row.subscribedRatio }} </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否提交投资者适当性材料')" align="center">
          <template slot-scope="scope">
            <span :style="scope.row.isSubmitInvestor === 'Y'?'color:#67c23a':'color:#f56c6c'">{{ isSubmitInvestorFormat(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="seen" :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="seen" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addHandle">{{ $t("添加") }}</el-button>
      </div>
      <FileTable :list.sync="form.fileList" data-type="fund_agreement" :business-id="autoBusinessId($route.query.id, form)" />
    </el-form>
  </div>
</template>

<script>
    import { saveFundAgreement, getFundAgreement, getByWfNodeId, delFundAgreementLp } from '@/api/fund/wfForm/fundAgreement'
    export default {
        data() {
            return {
                seen: false,
                // 表单参数
                form: {
                  // 出资人列表
                  fundAgreementLpList: []
                },
                // 遮罩层
                loading: false,
                // 是否基金扩大募集字典
                isFundEnlargeOptions: [],
                // 出资人类型字典
                typeOptions: [],
                // 合伙人类型字典
                partnerTypeOptions: [],
               // 是否提交投资者适当性材料
                isSubmitInvestorOptions: [],
                // 表单校验
                rules: {
                  applyTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  totalSubscriptionAmount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  isFundEnlarge: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  addSubscribedAmount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
              AgreementLpListRules: {
                timeSubscription: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                subscribedAmount: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
            }
            }
        },
        watch: {
          // 监听出资人列表数据
          'form.fundAgreementLpList': {
            handler(val) {
              this.form.totalSubscriptionAmount = 0
              if (val != null) {
                val.forEach((e) => {
                  this.form.totalSubscriptionAmount += e.subscribedAmount
                })
              }
            },
            deep: true
          }
        },
        created() {
            this.$bus.$emit('async_done')
            this.getDicts('sys_yes_no').then(response => {
                this.isFundEnlargeOptions = response.data
            })
            // 出资人类型
            this.getDicts('lp_type').then(response => {
            response.data.forEach(item => {
              this.typeOptions.push(item)
            })
            this.getDicts('main_body_type').then(response => {
              response.data.forEach(item => {
                this.typeOptions.push(item)
              })
            })
            })
             // 合伙人类型
            this.getDicts('partner_type').then(response => {
            this.partnerTypeOptions = response.data
          })
            // 是否提交投资者适当性材料
          this.getDicts('sys_yes_no').then(response => {
            this.isSubmitInvestorOptions = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getFundAgreement(data.id).then(response => {
                        this.form = response.data
                        this.percentageCalculation()
                        this.loading = false
                    })
                } else {
                  getByWfNodeId(data.wfNodeId).then(response => {
                    this.form = response.data
                    this.form.fileList = data.fileList
                    this.form.applyTitle = data.actTitle
                    this.percentageCalculation()
                    this.loading = false
                  })
                }
            },
            // 出资人类型字典
          typeFormat(row) {
              return this.selectDictLabel(this.typeOptions, row.type)
            },
            // 合伙企业
          partnerTypeFormat(row) {
            return this.selectDictLabel(this.partnerTypeOptions, row.partnerType)
           },
          // 是否提交投资者适当性材料
          isSubmitInvestorFormat(row) {
            return this.selectDictLabel(this.isSubmitInvestorOptions, row.isSubmitInvestor)
          },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    fundId: undefined,
                    fundName: undefined,
                    applyTitle: undefined,
                    totalSubscriptionAmount: undefined,
                    isFundEnlarge: undefined,
                    addSubscribedAmount: undefined,
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,

                  fundAgreementLpList: []

                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            /** 提交按钮 */
            submitForm: function() {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  // this.form.fundAgreementLpList.forEach(item => {
                  //   if (item.isSubmitInvestor === 'N') {
                  //     if (valid) {
                  //       this.msgError(this.$t('有出资人未提交投资者适当性材料!'))
                  //       valid = false
                  //     }
                  //   }
                  // })
                  if (valid) {
                    this.loading = true
                    saveFundAgreement(this.form).then(response => {
                      if (response.code === 200) {
                        // this.form.id = response.data.id
                        this.msgSuccess(this.$t('保存成功'))
                        this.loading = false
                        resolve(response.data.id)
                      } else {
                        this.msgError(response.msg)
                        this.loading = false
                        reject(response)
                      }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    this.locationError(document)
                    reject()
                  }
                })
              })
            },
          // 计算认缴比例百分比
          percentageCalculation() {
            var temp = 0
            this.form.fundAgreementLpList.forEach(item => {
              temp += item.subscribedAmount
            })
            var noLastRatio = 0
            this.form.fundAgreementLpList.forEach((item, index) => {
              var ratioTemp = (item.subscribedAmount / temp) * 100
              if (isNaN(ratioTemp)) {
                ratioTemp = 0
              }
              item.subscribedRatio = ratioTemp.toFixed(4)
              if (this.form.fundAgreementLpList === null) {
                this.form.fundAgreementLpList = ''
              }
              if (index === this.form.fundAgreementLpList.length - 1 && !isNaN(noLastRatio)) {
                if (parseFloat(item.subscribedRatio) <= 0) {
                  item.subscribedRatio = 0
                } else {
                  item.subscribedRatio = (100.0000 - noLastRatio).toFixed(4)
                }
              } else {
                noLastRatio += parseFloat(item.subscribedRatio)
              }
            })
          },
          // 添加出资人列表
          addHandle() {
              const row = {
                id: undefined,
                fundId: undefined,
                agreeId: undefined,
                investorId: undefined,
                type: undefined,
                partnerType: undefined,
                timeSubscription: undefined,
                subscribedAmount: undefined,
                subscribedRatio: undefined,
                isSubmitInvestor: undefined
              }
            if (!(this.form.fundAgreementLpList instanceof Array)) {
              this.$set(this.form, 'fundAgreementLpList', [])
            }
            this.$nextTick(() => {
              this.form.fundAgreementLpList.push(row)
            })
          },
          // 出资人列表删除
          delHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delFundAgreementLp(id)
                }).then(() => {
                this.form.fundAgreementLpList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.fundAgreementLpList.splice(index, 1)
            }
          }
        }
    }
</script>
